package flink_demo;

import org.apache.flink.api.common.ExecutionMode;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.ExecutionEnvironmentFactory;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 *
 * @author Spring_Hu
 * @date 2021/10/9
 */
public class Flink_demo02 {
    public static void main(String[] args) throws Exception {
        //flink 流处理1 读文件

        StreamExecutionEnvironment en = StreamExecutionEnvironment.getExecutionEnvironment();

        en.setRuntimeMode(RuntimeExecutionMode.BATCH);
        DataStreamSource<String> ds = en.readTextFile("test/word.txt");

        SingleOutputStreamOperator<Tuple2<String, Long>> result = ds.flatMap(new FlatMapFunction<String, String>() {
            public void flatMap(String line, Collector<String> collector) throws Exception {
                for (String word : line.split(" ")) {
                    collector.collect(word);
                }
            }
        }).map(new MapFunction<String, Tuple2<String, Long>>() {
            public Tuple2<String, Long> map(String word) throws Exception {
                return Tuple2.of(word, 1L);
            }
        }).keyBy(new KeySelector<Tuple2<String, Long>, String>() {
            public String getKey(Tuple2<String, Long> value) throws Exception {
                return value.f0;
            }
        }).sum(1);

        result.print();
        en.execute();

    }
}
